//
//  EngIndexController_Gtasks.m
//  Estate
//
//  Created by heyong on 16/9/6.
//  Copyright © 2016年 ttsx. All rights reserved.
//


#import "EngIndexController_Gtasks.h"
#import "EngLeaderIndexController.h"
#import "NewInspectionTextCell.h"
#import "InspectionGtasksTaskVC.h"

@interface EngIndexController_Gtasks ()

@end

@implementation EngIndexController_Gtasks

- (NSMutableArray *)dataArray{
    if(_dataArray==nil){
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, (DEF_SCREEN_HEIGHT-84-35*BIZ))];
        [LSUtility setExtraCellLineHidde:_tableView tabHeader:NO tabFooter:NO];
        [_tableView registerNib:[UINib nibWithNibName:@"NewInspectionTextCell" bundle:nil] forCellReuseIdentifier:@"detail"];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    [self.view addSubview: self.tableView];
    [self initDataSource];
  
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(initDataSource) name:@"Refresh_xjrw" object:nil];
}

//初始化数据
- (void)initDataSource
{
    [self.dataArray removeAllObjects];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    /*
     *  根据项目id 巡检组id
     */
//    NSString *sql_1= [NSString stringWithFormat:@"select count(1),substr(INSPECT_START_TIME,1,4) as year,substr(INSPECT_START_TIME,6,2) as month,substr(INSPECT_START_TIME,9,2) as day from inspect_process where inspect_group_id IN (select inspect_group_id from inspect_group_user where INSPECT_USER_ID ='%@' and INSPECT_USER_TYPE='1') and pro_id='%@'  GROUP BY substr(INSPECT_START_TIME,1,4) order by(year) desc",USERID,PROID];
    
    NSString *sql_1= [NSString stringWithFormat:@"select count(1),substr(inspect_start_time,1,4) as year,substr(inspect_start_time,6,2) as month,substr(inspect_start_time,9,2) as day from inspect_process where INSPECT_STATE!='5' and INSPECT_STATE!='' and inspect_group_id IN (select inspect_group_id from inspect_group_user where INSPECT_USER_ID ='%@' )GROUP BY(year) ORDER BY(year) desc",USERID];

    FMResultSet *result=[db executeQuery:sql_1];
    
    NSMutableDictionary *dic;
    
    while ([result next]) {
        NSString *year= [result stringForColumn:@"year"];
        NSString *sqlStr;
        sqlStr=[NSString stringWithFormat:@"SELECT *,substr(INSPECT_START_TIME,6,2) as month,substr(INSPECT_START_TIME,9,2) as day from INSPECT_PROCESS where substr(INSPECT_START_TIME,1,4)='%@' and INSPECT_STATE!='5' and INSPECT_STATE!='' and inspect_group_id IN (select inspect_group_id from inspect_group_user where INSPECT_USER_ID ='%@' ) order by(CREATE_TIME) desc",year,USERID];
        
        FMResultSet *results=[db executeQuery:sqlStr];
        //查询到记录
        NSMutableArray *DetailArr=[NSMutableArray array];
        while ([results next]) {
            NSString *month =[LSUtility deletaeZero:[results stringForColumn:@"month"]];
            NSString *day =[LSUtility deletaeZero:[results stringForColumn:@"day"]];
//            NSString *ids=[results stringForColumn:@"ID"];
            //查询结果转换成字典
            NSDictionary *resuDid=[results resultDictionary];
            NSMutableDictionary *dic=[[NSMutableDictionary alloc]initWithDictionary:resuDid];
            //设置标题
            NSString *title=[NSString stringWithFormat:@"%@月%@日_%@",month,day,dic[@"INSPECT_NAME"]];

            [dic setObject:title forKey:@"monthTitle"];
            //查询是否一键汇总
//           NSArray *typeArr= [LSUtility getTotalByProcessID:ids];
//            NSString *type=@"show";
//            if(typeArr.count>0){
//                type=@"no";
//            }
            //查询当前任务状态
            NSString *type=[results stringForColumn:@"INSPECT_STATE"];
            if([type isEqualToString:@"1"]){
                type=@"待巡检";
            }else if ([type isEqualToString:@"2"]){
                type=@"待汇总";
            }else if ([type isEqualToString:@"3"]){
                type=@"待整改";
            }else if ([type isEqualToString:@"4"]){
                type=@"待审阅";
            }else if ([type isEqualToString:@"5"]){
                type=@"已完成";
            }
            //设置状态
            [dic setObject:type forKey:@"type"];
            [DetailArr addObject:dic];
        }
        
        NSString *counts=[result stringForColumn:@"COUNT(1)"];
        if(![counts isEqualToString:@"0"]){
            NSString *tiemAndCount=[NSString stringWithFormat:@"%@年 (%@条)",year,counts];
            //创建一个字典 包含数组，分组名，是否展开的标示
            dic=[[NSMutableDictionary alloc] initWithObjectsAndKeys:DetailArr,DIC_ARARRY,tiemAndCount,DIC_TITILESTRING,[NSNumber numberWithInt:0],DIC_EXPANDED,nil];
            //将字典加入数组
            [self.dataArray addObject:dic];
        }
    }
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 40*BIZ)];
    if (!(self.dataArray.count > 0)) {
        label.text = @"您已没有要巡检的任务了!";
        label.textAlignment=1;
        label.font = [UIFont systemFontOfSize:24*BIZ];
        label.textColor=UIColorFromRGB(0x787878);
        [self.view addSubview:label];
    }else{
        [label removeFromSuperview];
    }


    [self.tableView reloadData];
    
    [db close];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section=indexPath.section;
    long row=indexPath.row;
    //得到改组下信息
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *reDic=array[row];
    
    NewInspectionTextCell *cell=[NewInspectionTextCell cellWithTableView:tableView];
    cell.title.text=[reDic objectForKey:@"monthTitle"];
    cell.state.text=reDic[@"type"];
    return  cell;
}

//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH,(CELL_HEIGHT-5)*BIZ)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    
    //设置分组标题
    [eButton setTitle:[[self.dataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:16.*BIZ];
    
    //设置button的图片和标题的相对位置
    
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    UIImage *image=eButton.imageView.image;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, image.size.width)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(0, eButton.titleLabel.bounds.size.width+20, 0, -eButton.titleLabel.bounds.size.width)];
    
    //添加btn
    [hView addSubview: eButton];
    return hView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 5;
    }else{
        return 0.1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *reDic=array[indexPath.row];
    return [self cellHeightWithObj: [reDic objectForKey:@"monthTitle"]];;
}


- (CGFloat)cellHeightWithObj:(NSString *)string{
    CGFloat cellHeight = 60;
    CGFloat mWidth = [UIScreen mainScreen].bounds.size.width - 100;
    cellHeight = [string boundingRectWithSize:CGSizeMake(mWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17*BIZ]} context:nil].size.height;
    if(cellHeight<=60){
        return 60;
    }else{
        return cellHeight;
    }
}

//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46*BIZ;
}

#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *reDic=array[indexPath.row];
    //判断角色
    NSString *groupId=reDic[@"INSPECT_GROUP_ID"];
    BOOL isLeader=[LSUtility queryInspcetGroupLeader:groupId];
    if(isLeader){
        EngLeaderIndexController *leader=[[EngLeaderIndexController alloc]init];
        leader.identifier=@"detail";
        leader.finsh=NO;
        NSString *processId=[reDic objectForKey:@"ID"];
        leader.processId=processId;
        [self.navigationController pushViewController:leader animated:YES];
    }else{
        InspectionGtasksTaskVC *gtasksTaskVC = [[InspectionGtasksTaskVC alloc] init];
        gtasksTaskVC.IPID = [reDic objectForKey:@"ID"];
        [self.navigationController pushViewController:gtasksTaskVC animated:YES];
    }
}

#pragma mark -- 内部调用
//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section{
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
    }else
    {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
}

//返回指定节是否是展开的
-(int)isExpanded:(long)section{
    NSDictionary *dic=[self.dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

//按钮被点击时触发
-(void)expandButtonClicked:(id)sender{
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
